package com.auction.system.task;

import com.auction.system.domain.dto.auction.AuctionGood;
import com.auction.system.domain.dto.auction.OrderInfo;
import com.auction.system.domain.query.auction.AuctionGoodQuery;
import com.auction.system.enums.EnumAuctionStatus;
import com.auction.system.enums.EnumDateStyle;
import com.auction.system.enums.EnumOrderStatus;
import com.auction.system.service.auction.IAuctionGoodService;
import com.auction.system.service.auction.IOrderInfoService;
import com.auction.system.utils.DateUtil;
import com.auction.system.utils.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @ClassName TimeTask
 * @Author 王伟学
 * @Version 1.0
 **/
@Component
@Slf4j
public class TimeTask {

    @Autowired
    private IAuctionGoodService auctionGoodService;

    @Autowired
    private IOrderInfoService orderInfoService;

    /**
     * 定时任务，校验拍卖截止时间是否到达（两分钟执行一次）
     */
    @Scheduled(fixedRate=120000)
    public void checkoutTime(){
        /**
         * 两分钟执行一次，验证竞拍中的拍品结束时间是否到达，
         * 若到达，判断是否存在最高价竞拍人（即有竞价记录）。
         * 若有，生成订单数据，将拍品状态置为竞价成功；若无，将拍品状态置为流拍
         */
        AuctionGoodQuery auctionGoodQuery = new AuctionGoodQuery();
        auctionGoodQuery.setEndTimeEnd(DateUtil.getCurrentTime(EnumDateStyle.YYYY_MM_DD_HH_MM_SS));
        auctionGoodQuery.setAuctionStatus(EnumAuctionStatus.BIDDING.getCode());
        List<AuctionGood> auctionGoods = auctionGoodService.getList(auctionGoodQuery);
        if(StringUtil.isNotEmpty(auctionGoods)){
            for(AuctionGood auctionGood : auctionGoods){
                if(StringUtil.isNull(auctionGood.getMaxPriceUserId()) || auctionGood.getMaxPriceUserId() == 0){
                    //无最高价竞拍人,流拍
                    auctionGood.setAuctionStatus(EnumAuctionStatus.BID_ERROR.getCode());
                    auctionGoodService.edit(auctionGood);
                }else{
                    //有最高价，竞价成功，生成订单信息
                    auctionGood.setAuctionStatus(EnumAuctionStatus.BID_SUCCESS.getCode());
                    auctionGoodService.edit(auctionGood);
                    OrderInfo orderInfo = new OrderInfo();
                    orderInfo.setBuyerId(auctionGood.getMaxPriceUserId());
                    orderInfo.setGoodId(auctionGood.getId());
                    orderInfo.setSellerId(auctionGood.getBidUserId());
                    orderInfo.setOrderStatus(EnumOrderStatus.TO_TRADE.getCode());
                    orderInfoService.add(orderInfo);
                }
            }
        }
    }
}
